import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:path_provider/path_provider.dart';
import 'package:content/model/jsonModel.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'XX集团通讯录',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
    @override
  void initState(){
    super.initState();
    justLogin();
  }
  Future<String> getupdatetime() async {
  String updatetime;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    updatetime = prefs.getString('updatetime');
  return updatetime;
}
  justLogin() async {
    String updatetime =await getupdatetime();
    if(updatetime == null){
      Navigator.pushReplacement(
        context,
        new MaterialPageRoute(builder: (context) => new LoginPage()),
      );
    }else{
      String apiupdatetime;
      try{
        var _content;
        Dio dio = new Dio();
        var response = await dio.get("获取更新日期的接口",queryParameters:{"kouling":"口令"});
        _content = response.data.toString();
        final  _contentJson = jsonDecode(_content);
        apiupdatetime = _contentJson['result'].toString();
        }catch(e){
        print(e);
        }
      var d1 = DateTime.parse(updatetime);
      var d2 = DateTime.parse(apiupdatetime);
      if(d1.isAtSameMomentAs(d2)){
        print('不更新');
      }else
      {
      getUpdatenow();
      }
    }
  }
  
   Future<File> _getLocalFile() async {
    // get the path to the document directory.
    String dir = (await getApplicationDocumentsDirectory()).path;
    return new File('$dir/counter.json');
  }

  Future<Null> writeResult(_contentJson) async {
    // write the variable as a string to the file
    await (await _getLocalFile()).writeAsString('$_contentJson');
  }
  Future getUpdatenow() async{
    try{
      Response response;
        Dio  dio =  new   Dio();
      response = await dio.post("获取数据的地址", data: {"kouling":"口令"});
      writeResult(response.data); 
    }catch(e){
      print(e);
    }
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('XX集团通讯录'),
        actions:<Widget>[
          IconButton(
            icon:Icon(Icons.search),
            onPressed: (){
              showSearch(context: context,delegate: SearchBarDelegate());
            },
          ),
        ]
      ),
      
      body: new Center(
      child: new Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,        //对齐方式：平均间隔
        children: [
            new ListTile(
              leading:new Icon(Icons.star),
              title:new Text('一级单位'),
              trailing: Icon(Icons.keyboard_arrow_right),
              onTap: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) => new DataAppPage(title:'一级单位')),
                );
              },
            ),
            new ListTile(
              leading:new Icon(Icons.star),
              title:new Text('二级单位1'),
              trailing: Icon(Icons.keyboard_arrow_right),
              onTap: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) => new DataAppPage(title:'二级单位1')),
                );
              },
            ),
              new ListTile(
              leading:new Icon(Icons.star),
              title:new Text('二级单位2'),
              trailing: Icon(Icons.keyboard_arrow_right),
              onTap: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) => new DataAppPage(title:'二级单位2')),
                );
              },
            ),
              new ListTile(
              leading:new Icon(Icons.star),
              title:new Text('二级单位3'),
              trailing: Icon(Icons.keyboard_arrow_right),
              onTap: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) => new DataAppPage(title:'二级单位3')),
                );
              },
            ),
              new ListTile(
              leading:new Icon(Icons.star),
              title:new Text('二级单位4'),
              trailing: Icon(Icons.keyboard_arrow_right),
              onTap: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) => new DataAppPage(title:'二级单位4')),
                );
              },
            ),
              new ListTile(
              leading:new Icon(Icons.star),
              title:new Text('二级单位5'),
              trailing: Icon(Icons.keyboard_arrow_right),
              onTap: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) => new DataAppPage(title:'二级单位5')),
                );
              },
            ),
              new ListTile(
              leading:new Icon(Icons.star),
              title:new Text('二级单位6'),
              trailing: Icon(Icons.keyboard_arrow_right),
              onTap: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) => new DataAppPage(title:'二级单位6')),
                );
              },
            ),
              new ListTile(
              leading:new Icon(Icons.star),
              title:new Text('二级单位7'),
              trailing: Icon(Icons.keyboard_arrow_right),
              onTap: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) => new DataAppPage(title:'二级单位7')),
                );
              },
            ),
        ]
      )
    )
    );
  }
}
class DataAppPage extends StatefulWidget {
  DataAppPage({Key key, @required this.title})
      : super(key: key);
  final String title;
  @override
  State<StatefulWidget> createState() {
    return new _DataAppPageState();
  }
}
class _DataAppPageState extends State<DataAppPage> {
  String title;
  List<String> letters = [];
  List<PhoneCompanyData> data;
  List<PhonePyData> _data;
  ScrollController _scrollController = ScrollController();
  int _currentIndex = 0;
  Future<File> _getLocalFile() async {
      // get the path to the document directory.
      String dir = (await getApplicationDocumentsDirectory()).path;
      return new File('$dir/counter.json');
    }
  readJSON() async {
    try {
        File file = await _getLocalFile();
        String str = await file.readAsString();
        return str;
    }
    catch (err) {
        print(err);
    }
    }
  @override
  void initState(){
    title = widget.title;
    super.initState();
    getPhoneCodeDataList();
  }
   getPhoneCodeDataList() async {
    var response = await readJSON();
    var resultUser = new PhoneCompanyEntity.fromJson(json.decode(response));
    data = resultUser.data;
    data.forEach((element) {
      //(element.company);
      //print(title);
      if (element.company== title) {
      //数据库有数据
      _data=element.listData;
    }
    });
    for (int i = 0; i < _data.length; i++) {
      letters.add(_data[i].py);
    }
    setState(() {});
  }
  Future<void> _makePhoneCall(String url) async {
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("$title"),
        centerTitle: true,
      ),
      body: Stack(
        children: <Widget>[
          data == null || data.length == 0
              ? Text("")
              : Padding(
                  padding: EdgeInsets.only(left: 20),
                  child: ListView.builder(
                      controller: _scrollController,
                      itemCount: _data.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            PhoneCodeIndexName(_data[index].py),
                            ListView.builder(
                                itemBuilder:
                                    (BuildContext context, int index2) {
                                  return Container(
                                    height: 46,
                                    child: GestureDetector(
//                      behavior: HitTestBehavior.translucent,
                                      child: Padding(
                                        padding:
                                            EdgeInsets.symmetric(vertical: 10),
                                        child: Row(
                                          children: <Widget>[
                                            Text(
                                                "${_data[index].listData[index2].userName}",
                                                style: TextStyle(
                                                    fontSize: 16,
                                                    color: Color(0xff434343))),
                                            Margin(width: 10),
                                            Text(
                                              "   ${_data[index].listData[index2].shortNumber}",
                                              style: TextStyle(
                                                  fontSize: 16,
                                                  color: Color(0xffD6D6D6)),
                                            )
                                          ],
                                        ),
                                      ),
                                    onTap: () {
                                      showDialog<Null>(
                                      context: context,
                                      builder: (BuildContext context) {
                                          final String userName = _data[index].listData[index2].userName; 
                                          final String phoneNumber = _data[index].listData[index2].phoneNumber; 
                                          final String shortNumber = _data[index].listData[index2].shortNumber; 
                                          return new SimpleDialog(
                                              title: new Text("$userName"),
                                              children: <Widget>[
                                                  new SimpleDialogOption(
                                                      child: new Text('拨打手机号码：$phoneNumber'),
                                                      onPressed: () => 
                                                      _makePhoneCall('tel:$phoneNumber'),
                                                  ),
                                                  new SimpleDialogOption(
                                                      child: new Text('发送手机短信：$phoneNumber'),
                                                      onPressed: () => 
                                                      _makePhoneCall('sms:$phoneNumber'),
                                                  ),
                                                  new SimpleDialogOption(
                                                      child: new Text('拨打手机短号：$shortNumber'),
                                                      onPressed: () => 
                                                      _makePhoneCall('tel:$shortNumber'),
                                                  ),
                                              ],
                                          );
                                      },
                                  ).then((val) {
                                      print(val);
                                  });
                              },
                                    ),
                                    decoration: BoxDecoration(
                                  border: Border(bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))
                                ),
                                  );
                                },
                                itemCount: _data[index].listData.length,
                                shrinkWrap: true,
                                physics:
                                    NeverScrollableScrollPhysics()) //禁用滑动事件),
                          ],
                        );
                      }),
                ),
          Align(
            alignment: new FractionalOffset(1.0, 0.5),
            child: SizedBox(
              width: 25,
              child: Padding(
                padding: EdgeInsets.only(top: 20),
                child: ListView.builder(
                  itemCount: letters.length,
                  itemBuilder: (BuildContext context, int index) {
                    return GestureDetector(
                      child: Text(
                        letters[index],
                        style: TextStyle(color: Colors.black),
                      ),
                      onTap: () {
                        setState(() {
                          _currentIndex = index;
                        });
                        var height = index * 45.0;
                        for (int i = 0; i < index; i++) {
                          height += _data[i].listData.length * 46.0;
                        }
                        _scrollController.jumpTo(height);
                      },
                    );
                  },
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
class PhoneCodeIndexName extends StatelessWidget {
  String indexName;
  PhoneCodeIndexName(this.indexName);

  Widget build(BuildContext context) {
    return Container(
      height: 45,
      child: Padding(
        child: Text(indexName,
            style: TextStyle(fontSize: 20, color: Color(0xff434343))),
        padding: EdgeInsets.symmetric(vertical: 10),
      ),
    );
  }
}
class Margin extends StatelessWidget {
  double width, height;

  Margin({this.width = 0, this.height = 0});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: height,
      width: width,
    );
  }
}
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
  final _userName = TextEditingController(); //用户名
  final _userPwd = TextEditingController(); //密码
  GlobalKey _globalKey = new GlobalKey<FormState>(); //用于检查输入框是否为空
  void judgelogin(phonenumber,kouling) async {
    var _content;
    Dio dio = new Dio();
    var response = await dio.get("首次登陆信息",queryParameters:{"phonenumber":phonenumber,"kouling":kouling});
    _content = response.data.toString();
    final  _contentJson = jsonDecode(_content);
    String result = _contentJson['result'].toString();
    showDialog(
        context: context,
        builder: (context) {
          if (result== "yes") {
            saveLogin(phonenumber);
            String sucess = "登录成功 \n" + _userName.text;
            return AlertDialog(
              content: Text(sucess),
              actions: <Widget>[
                        new FlatButton(
                            child: new Text('确定'),
                            onPressed: () {
                                    Navigator.push(
                                      context,
                                      new MaterialPageRoute(builder: (context) => new MyHomePage()),
                                    );
                                  },
                        ),
                    ],
            );   
          } else {
            String err = "登录失败 \n 账号或密码错误";
            return AlertDialog(
              content: Text(err),
            );
          }
        });
  }
  Future<String> saveLogin(loginphone) async {
  var userName;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('loginphone', loginphone);
    prefs.setString('updatetime', '20200101');
  return userName;
}
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('登录'),
      ),
      body: Center(
        child: Form(
          key: _globalKey,
          autovalidate: true, //自动校验
          child: Column(
            children: <Widget>[
              TextFormField(
                controller: _userName,
                decoration: InputDecoration(
                    labelText: "手机号码",
                    hintText: "输入你的手机号码",
                    icon: Icon(Icons.person)),
                validator: (v) {
                  return v.trim().length > 0 ? null : "用户名不能为空";
                },
              ),
              TextFormField(
                controller: _userPwd,
                decoration: InputDecoration(
                  labelText: "口令",
                  hintText: "输入口令",
                  icon: Icon(Icons.lock),
                ),
                obscureText: true,
              ),
              Padding(
                padding: EdgeInsets.only(top: 20.0),
              ),
              SizedBox(
                width: 120.0,
                height: 50.0,
                child: RaisedButton(
                  onPressed: () {
                    if ((_globalKey.currentState as FormState).validate()) {
                      judgelogin(_userName.text,_userPwd.text);
                    }
                  },
                  child: Text(
                    "登录",
                    style: TextStyle(color: Colors.white), //字体白色
                  ),
                  color: Colors.blue,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class SearchBarDelegate extends SearchDelegate<String> {
  @override
  List<Widget> buildActions(BuildContext context) {
    //右侧显示内容 这里放清除按钮
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = "";
          showSuggestions(context);
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    //左侧显示内容 这里放了返回按钮
    return IconButton(
      icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
      onPressed: () {
        if (query.isEmpty) {
          close(context, null);
        } else {
          query = "";
          showSuggestions(context);
        }
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    //点击了搜索显示的页面    
    return SearchResultsView(query:query);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    //点击了搜索窗显示的页面
    return Center(
    );
  }

  @override
  ThemeData appBarTheme(BuildContext context) {
    return super.appBarTheme(context);
  }
}
class SearchResultsView extends StatefulWidget {
  SearchResultsView({Key key, @required this.query})
      : super(key: key);
  final String query;
  @override
  _SearchResultsState createState() => _SearchResultsState();
}
class _SearchResultsState extends State<SearchResultsView> {
  String query;
  List<PhoneSearchDataListdata> _datas;
  int dataLength;
  @override
  void initState() {
    query = widget.query;
    super.initState();
    _getDataFromGet();
  }
  _getDataFromGet() async {
    var _content;
    Dio dio = new Dio();
    var response = await dio.get("查询接口",queryParameters:{"query":query});
    _content = response.data.toString();
    var result = new PhoneSearchData.fromJson(json.decode(_content));
    _datas = result.listData;
    setState(() {});
  }
  Future<void> _makePhoneCall(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: Stack(
        children: <Widget>[
          _datas == null || _datas.length == 0
              ? Text("")
              : Padding(
                  padding: EdgeInsets.only(left: 20),
                  child: 
                        new ListView.separated(
        itemBuilder: (context, index) {
          return new ListTile(
            title: new Text(_datas[index].userName+'  '+_datas[index].shortNumber),
            subtitle:new Text(_datas[index].userCompany),
            onTap: () {
            showDialog<Null>(
            context: context,
            builder: (BuildContext context) {
                final String userName = _datas[index].userName; 
                final String phoneNumber = _datas[index].phoneNumber; 
                final String shortNumber = _datas[index].shortNumber; 
                return new SimpleDialog(
                    title: new Text("$userName"),
                    children: <Widget>[
                        new SimpleDialogOption(
                            child: new Text('拨打手机号码：$phoneNumber'),
                            onPressed: () => 
                            _makePhoneCall('tel:$phoneNumber'),
                        ),
                        new SimpleDialogOption(
                            child: new Text('发送手机短信：$phoneNumber'),
                            onPressed: () => 
                            _makePhoneCall('sms:$phoneNumber'),
                        ),
                        new SimpleDialogOption(
                            child: new Text('拨打手机短号：$shortNumber'),
                            onPressed: () => 
                            _makePhoneCall('tel:$shortNumber'),
                        ),
                    ],
                );
            },
        ).then((val) {
            print(val);
        });
    },
          );
        },
        separatorBuilder: (context, index) {
        return Divider();
      },
      itemCount:_datas.length,
      ),
                ),
        ],
      ),
    );
  }
  }